import NProgress from 'nprogress' // progress bar  进度条插件
import 'nprogress/nprogress.css' // progress bar style  进度条样式
import router from './router'
import store from './store'
import getPageTitle from '@/utils/get-page-title'
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
// 路由守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  const whiteList = ['/login', '/404'] // 白名单
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserProfile')
      }
      next()
    }
  } else {
    // 没有登录，只能去白名单(那些不需要token就可以访问的页面)
    // 检查当前要访问的路径是否在whiteList中存在
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
